import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  NavBar,
  Image,
  Checkbox,
  Stepper,
  SwipeAction,
  Empty,
  Button,
  Toast,
  Dialog
} from 'antd-mobile';
import './Cart.css';

// 购物车页面
const Cart = () => {
  const navigate = useNavigate();
  const [cartItems, setCartItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [checkedAll, setCheckedAll] = useState(false);
  const [totalPrice, setTotalPrice] = useState(0);
  const [totalCount, setTotalCount] = useState(0);

  // 加载购物车数据
  useEffect(() => {
    setLoading(true);

    // 从本地存储获取购物车数据
    const storedCartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
    setCartItems(storedCartItems);

    setLoading(false);
  }, []);

  // 更新全选状态、总价和数量
  useEffect(() => {
    const isAllChecked = cartItems.length > 0 && cartItems.every(item => item.checked);
    setCheckedAll(isAllChecked);

    const checkedItems = cartItems.filter(item => item.checked);
    const total = checkedItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
    const count = checkedItems.reduce((sum, item) => sum + item.quantity, 0);

    setTotalPrice(total);
    setTotalCount(count);
  }, [cartItems]);

  // 更新本地存储
  const updateLocalStorage = (newCartItems) => {
    localStorage.setItem('cartItems', JSON.stringify(newCartItems));
  };

  // 切换商品选中状态
  const toggleItemCheck = (id) => {
    const newCartItems = cartItems.map(item => {
      if (item.id === id) {
        return { ...item, checked: !item.checked };
      }
      return item;
    });

    setCartItems(newCartItems);
    updateLocalStorage(newCartItems);
  };

  // 切换全选状态
  const toggleCheckAll = () => {
    const newCheckedAll = !checkedAll;
    const newCartItems = cartItems.map(item => ({
      ...item,
      checked: newCheckedAll
    }));

    setCartItems(newCartItems);
    updateLocalStorage(newCartItems);
  };

  // 更新商品数量
  const updateItemQuantity = (id, quantity) => {
    const newCartItems = cartItems.map(item => {
      if (item.id === id) {
        return { ...item, quantity };
      }
      return item;
    });

    setCartItems(newCartItems);
    updateLocalStorage(newCartItems);
  };

  // 删除商品
  const removeItem = (id) => {
    Dialog.confirm({
      content: '确定要删除该商品吗？',
      onConfirm: () => {
        const newCartItems = cartItems.filter(item => item.id !== id);
        setCartItems(newCartItems);
        updateLocalStorage(newCartItems);
        Toast.show({
          icon: 'success',
          content: '删除成功',
        });
      },
    });
  };

  // 结算
  const checkout = () => {
    if (totalCount === 0) {
      Toast.show({
        icon: 'fail',
        content: '请选择要结算的商品',
      });
      return;
    }

    // 筛选出选中的商品作为订单项
    const orderItems = cartItems
      .filter(item => item.checked)
      .map(({ id, name, price, image, quantity }) => ({
        id,
        name,
        price,
        image,
        quantity
      }));

    // 保存订单项到本地存储
    localStorage.setItem('tempOrderItems', JSON.stringify(orderItems));

    // 跳转到订单创建页面
    navigate('/order/create');
  };

  // 返回首页
  const back = () => {
    navigate('/home');
  };

  return (
    <div className="cart-container">
      {/* 导航栏 */}
      <NavBar onBack={back}>购物车</NavBar>

      {/* 购物车列表 */}
      <div className="cart-content">
        {loading ? (
          <div className="loading-container">
            <div className="loading-spinner">加载中...</div>
          </div>
        ) : cartItems.length === 0 ? (
          <div className="empty-cart">
            <Empty description="购物车还是空的" />
            <Button
              color='primary'
              fill='solid'
              onClick={() => navigate('/home')}
              style={{ marginTop: '20px' }}
            >
              去逛逛
            </Button>
          </div>
        ) : (
          <div className="cart-list">
            {cartItems.map(item => (
              <SwipeAction
                key={item.id}
                rightActions={[
                  {
                    key: 'delete',
                    text: '删除',
                    color: 'danger',
                    onClick: () => removeItem(item.id)
                  }
                ]}
              >
                <div className="cart-item">
                  <div className="item-check">
                    <Checkbox
                      checked={item.checked}
                      onChange={() => toggleItemCheck(item.id)}
                    />
                  </div>
                  <div className="item-image">
                    <Image
                      src={item.image}
                      fit='cover'
                      width={80}
                      height={80}
                      onClick={() => navigate(`/product/${item.id}`)}
                    />
                  </div>
                  <div className="item-info">
                    <div className="item-name" onClick={() => navigate(`/product/${item.id}`)}>
                      {item.name}
                    </div>
                    <div className="item-price">¥{item.price.toFixed(2)}</div>
                    <div className="item-quantity">
                      <Stepper
                        min={1}
                        max={99}
                        value={item.quantity}
                        onChange={(value) => updateItemQuantity(item.id, value)}
                      />
                    </div>
                  </div>
                </div>
              </SwipeAction>
            ))}
          </div>
        )}
      </div>

      {/* 底部结算栏 - 完全重建 */}
      {cartItems.length > 0 && (
        <div className="cart-bottom-space"></div>
      )}
      {cartItems.length > 0 && (
        <div className="cart-fixed-footer">
          <div className="cart-select-all">
            <Checkbox
              checked={checkedAll}
              onChange={toggleCheckAll}
            >
              全选
            </Checkbox>
          </div>
          <div className="cart-total-info">
            <div className="cart-total-price">
              合计: <span className="highlight-price">¥{totalPrice.toFixed(2)}</span>
            </div>
            <div className="cart-count">
              {totalCount > 0 ? `共${totalCount}件商品` : ''}
            </div>
          </div>
          <div className="cart-checkout-button">
            <button
              className={`checkout-btn ${totalCount === 0 ? 'disabled' : ''}`}
              onClick={totalCount > 0 ? checkout : undefined}
              disabled={totalCount === 0}
            >
              结算{totalCount > 0 ? `(${totalCount})` : ''}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default Cart; 